<?php

namespace App\Console\Commands;

use App\Models\User;
use Illuminate\Console\Command;
use Spatie\Permission\Models\Role;

class Init extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'shine:init';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '初始化系统，创建管理员账号，以及初始权限';

    /**
     * Execute the console command.
     */
    public function handle(): void
    {
        // 初始化管理员权限
        $adminRole = Role::findOrCreate('administrator');
        // 询问管理员账号密码
        $email = $this->ask('请输入管理员邮箱');
        $password = $this->ask('请输入管理员密码');

        $user = new User();
        $user->email = $email;
        $user->password = bcrypt($password);
        $user->name = $email;
        $suc = $user->save();
        if ($suc) {
            $user->assignRole($adminRole);
            $this->info('管理员账号以及管理员权限创建成功');
        } else {
            $this->error('管理员账号创建失败，请查看数据库邮箱是否存在');
        }
    }
}
